import os
import re

def split_novel(input_file, output_dir):
    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # 匹配章节标题及其内容，兼容“第652章XXXX”或“第652章 XXXX”
    pattern = re.compile(
        r'(第[\d]+章)\s*([^\n]+)\n(.*?)(?=^第[\d]+章\s*[^\n]+|\Z)',
        re.S | re.M
    )
    matches = pattern.findall(content)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for chapter_prefix, article_name, body in matches:
        # 文件名只保留文章名称，去除“第XX章”
        filename = re.sub(r'[\\/:*?"<>|]', '', article_name.strip()) + '.txt'
        filepath = os.path.join(output_dir, filename)
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(f"{chapter_prefix} {article_name}\n\n{body.strip()}")
        print(f'已生成: {filepath}')

def split_chapters(input_file, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # 匹配“单章 文章名”及其内容
    pattern = r'(章节目录\s+([^\n\r]+)[\n\r]+)(.*?)(?=(?:\n章节目录\s+[^\n\r]+[\n\r]+)|\Z)'
    matches = re.findall(pattern, content, re.DOTALL)

    for match in matches:
        chapter_title = match[1].strip()
        chapter_content = match[2].strip()
        filename = os.path.join(output_dir, f"{safe_filename(chapter_title)}.txt")
        with open(filename, 'w', encoding='utf-8') as f_out:
            f_out.write(chapter_content)
        print(f"已生成：{filename}")

def split_chapters_by_title(input_file, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # 使用全角空格+分隔符作为分割点
    parts = re.split(r'(?:\u3000\u3000[\/])', content)
    for part in parts:
        lines = [line.strip() for line in part.splitlines() if line.strip()]
        if not lines:
            continue
        title = lines[1]
        body = '\n'.join(lines[1:]).strip()
        if not body:
            continue
        filename = os.path.join(output_dir, f"{safe_filename(title)}.txt")
        with open(filename, 'w', encoding='utf-8') as f_out:
            f_out.write(body)
        print(f"已生成：{filename}")

def safe_filename(name):
    # 替换Windows不允许的文件名字符为下划线
    return re.sub(r'[\\/:*?"<>|]', '_', name)

if __name__ == "__main__":
    split_chapters('input.txt', 'output_chapters')

    